package top.infopub.zookeeper.test;


import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;


/**
 * 复制 zookeeper节点及节点数据 
 * @author Awoke
 * @version 2018年10月30日
 * @see CopyZkNode
 * @since
 */
public final class CopyZkNode {

    public static void main(String[] args)
        throws Exception {
        // 旧zk配置
        ZooKeeper oldzk = new ZooKeeper("47.103.44.90:13281", 60000, null);
        // 新zk配置
        ZooKeeper newzk = new ZooKeeper("127.0.0.1:2181", 60000, null);

        String[] pathEnds = {"dataChangeNotice", "info-mgr", "info-mgc", "info-job", "info-app", "info-ipc"};

        for (String pathEnd : pathEnds) {
            if (StringUtils.isNotBlank(pathEnd)) {
                // 迁移的节点
                String from_node = "/infopub/thjg/conf/" + pathEnd;
                String to_node = "/infopub/thjg/conf/" + pathEnd;

                List<String> children = oldzk.getChildren(from_node, false);
                for (int i = 0; i < children.size(); i++ ) {
                    System.out.println("child----" + children.get(i));
                }
                move(oldzk, newzk, children, from_node, to_node);
            }
        }
        oldzk.close();
        newzk.close();
    }

    private static void move(ZooKeeper oldzk, ZooKeeper newzk, List<String> children,
                             String from_node, String to_node)
        throws KeeperException, InterruptedException {
        if (children == null || children.isEmpty()) {
            return;
        }
        else {
            for (String child : children) {
                String from_c = from_node + "/" + child;
                String to_c = to_node + "/" + child;
                System.out.println("复制路径从：" + from_c + " 到：" + to_c);
                byte[] data = oldzk.getData(from_c, false, null);
                if (newzk.exists(to_c, false) == null) {
                    newzk.create(to_c, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
                else {
                    newzk.setData(to_c, data, -1, null, null);
                }
                move(oldzk, newzk, oldzk.getChildren(from_c, false), from_c, to_c);
            }
        }
    }
}
